package com.xiaoniu.timer.impl;

import com.xiaoniu.timer.Timer;
import com.xiaoniu.timer.TimerUtilsHelp;
import io.vertx.core.json.JsonObject;
import org.springframework.context.ApplicationContext;

import java.text.ParseException;

/**
 * Created by sweet on 2017/11/10.
 * ---------------------------
 */
public class TimerImpl extends TimerAbs {


  private TimerImpl() {
    super();
  }

  private TimerImpl(ApplicationContext context) {
    super(context);
  }

  public static Timer newInstance() {
    return new TimerImpl();
  }

  public static Timer newInstance(ApplicationContext context) {
    return new TimerImpl(context);
  }

  /**
   * 添加一次性任务
   *
   * @param time       时间表达式
   * @param className  要执行方法的类名
   * @param methodName 方法名
   * @param args       参数
   * @return 添加成功此次任务的 id
   */
  @Override
  public String addTimerJob(String time, String className, String methodName, String args) throws ParseException {
    String taskId = TimerUtilsHelp.uuid();
    long l = TimerUtilsHelp.dateToMillisecond(time) - System.currentTimeMillis();
    long execute = execute(taskId, l, className, methodName, args);
    log.debug("一次性任务，预计执行时间：" + TimerUtilsHelp.formatDate(System.currentTimeMillis() + l));
    ID_JOB.put(taskId, execute);
    JsonObject jsonObject = new JsonObject().put("className", className)
            .put("methodName", methodName).put("args", args).put("time", time).put("type", "time");
    TIMER_JOB.put(taskId, jsonObject);

    IDJOB_DB.put(taskId, execute);
    TIMEJOB_DB.put(taskId, jsonObject.toString());
    mapDb.commit();
    log.debug("添加一次性任务成功, taskId: " + taskId);
    return taskId;
  }

  /**
   * 添加周期性任务
   *
   * @param time       时间表达式
   * @param className  要执行方法的类名
   * @param methodName 方法名
   * @param args       参数
   * @return 添加成功，返回此任务的Id
   */
  @Override
  public String addPeriodicJob(String time, String className, String methodName, String args) {
    final String taskId = TimerUtilsHelp.uuid();
    Long timerId = executePeriodicJob(taskId, time, className, methodName, args);
    JsonObject jsonObject = new JsonObject().put("className", className)
            .put("methodName", methodName).put("args", args).put("time", time).put("type", "periodic");
    PERIODIC_JOB.put(taskId, jsonObject);
    ID_JOB.put(taskId, timerId);

    PERIODICJOB_DB.put(taskId, jsonObject.toString());
    IDJOB_DB.put(taskId, timerId);
    mapDb.commit();
    log.debug("添加周期性任务成功, taskId: " + taskId);
    return taskId;
  }

}
